package com.geeklan.smart.ui.login;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;

import com.geeklan.base.base.BaseActivity;
import com.geeklan.smart.MLMApplication;
import com.geeklan.smart.R;
import com.geeklan.smart.common.Constants;
import com.geeklan.smart.data.model.LoginResponse;
import com.geeklan.smart.data.model.User;
import com.geeklan.smart.data.model.UserInfo;
import com.geeklan.smart.data.remote.IpApiClient;
import com.geeklan.smart.data.repository.device.CmdRepository;
import com.geeklan.smart.data.repository.user.AccountRepository;
import com.geeklan.smart.databinding.ActivityLoginBinding;
import com.geeklan.smart.ui.main.MainActivity;
import com.geeklan.smart.ui.viewmodel.device.CmdViewModel;
import com.geeklan.smart.ui.viewmodel.device.CmdViewModelFactory;
import com.geeklan.smart.ui.viewmodel.user.UserViewModel;
import com.geeklan.smart.ui.viewmodel.user.UserViewModelFactory;
import com.geeklan.smart.ui.web.WebViewActivity;
import com.geeklan.smart.utils.AppUtils;
import com.geeklan.smart.utils.MD5Utils;
import com.geeklan.smart.utils.SharedPreferencesUtil;

public class LoginActivity extends BaseActivity<ActivityLoginBinding> {
    private UserViewModel userViewModel;
    private boolean isCheck = false;
    @Override
    protected ActivityLoginBinding initBinding() {
        return ActivityLoginBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void onApplyWindowInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }

    @Override
    protected void initView() {
        String username = SharedPreferencesUtil.getString("username","");
        mBinding.etInputAccount.setText(username);
        mBinding.tvRegister.setOnClickListener(v -> RegisterActivity.startRegister(this));
        mBinding.tvLogin.setOnClickListener(v -> {
            if(isCheck) {
                if(TextUtils.isEmpty(mBinding.etInputAccount.getText()) || TextUtils.isEmpty(mBinding.etInputPwd.getText())){
                    Toast.makeText(this, R.string.login_input_account_pwd_null,Toast.LENGTH_SHORT).show();
                    return;
                }

                loading();
                User user = new User();
                user.setUsername(mBinding.etInputAccount.getText().toString());
                user.setPassword(MD5Utils.encryptMD5(mBinding.etInputPwd.getText().toString() + "miaomojo"));
                user.setPhoneName(Build.BRAND + " " + Build.MODEL);
                user.setPhoneType(1);
                user.setIpAddress(SharedPreferencesUtil.getString("address_ip","119.123.207.198"));
                user.setMacAddress(AppUtils.getMacAddress());
                user.setAppVersion(AppUtils.getVersionName(getApplicationContext()));
                userViewModel.login(user);
            }else {
                Toast.makeText(this, R.string.Please_check_the_user_agreement,Toast.LENGTH_SHORT).show();
            }
        });
        mBinding.llCheck.setOnClickListener(v -> {
            if(isCheck){
                isCheck = false;
                mBinding.ivCheck.setImageDrawable(ActivityCompat.getDrawable(this,R.drawable.ic_checkbox_def));
            }else {
                isCheck = true;
                mBinding.ivCheck.setImageDrawable(ActivityCompat.getDrawable(this,R.drawable.ic_checkbox_select));
            }
        });

        mBinding.tvPrivacy.setOnClickListener(v -> {
            WebViewActivity.startActivity(this, Constants.PRIVACY_URL);
        });

        mBinding.tvUser.setOnClickListener(v -> {
            WebViewActivity.startActivity(this, Constants.USER_URL);
        });

        mBinding.ivVisibility.setOnClickListener(v -> {
            if (!isShowPwd) {
                isShowPwd = true;
                mBinding.ivVisibility.setImageResource(R.drawable.login_pwd_show);
                //显示
                mBinding.etInputPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            } else {
                isShowPwd = false;
                mBinding.ivVisibility.setImageResource(R.drawable.login_pwd_hint);
                //隐藏
                mBinding.etInputPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
        });
    }
    private boolean isShowPwd = false;
    @Override
    protected void initData() {
        IpApiClient apiClient = new IpApiClient();

        // 异步请求示例
        apiClient.getIpDataAsync();
        userViewModel = new ViewModelProvider(this, new UserViewModelFactory(new AccountRepository())).get(UserViewModel.class);

        userViewModel.getUserLiveData().observe(this, response -> {
            dismiss();
            if (response.getData() != null) {
                LoginResponse loginResponse = response.getData();
                SharedPreferencesUtil.putString("token",loginResponse.getToken());
                SharedPreferencesUtil.putUser(loginResponse.getUserinfo());
                MLMApplication.getUmeng().addAlias(String.valueOf(loginResponse.getUserinfo().getUserId()));
                MainActivity.startActivity(this);
                finish();
            } else {
                // 处理错误
            }
        });

        userViewModel.getErrorLiveData().observe(this, s -> {
            dismiss();
            Toast.makeText(this,s,Toast.LENGTH_SHORT).show();
        });
    }

    @Override
    public void networkStatus(boolean isConnected) {

    }

    @Override
    public void networkType(int type) {

    }

    public static void startLogin(Context context){
        Intent intent = new Intent(context,LoginActivity.class);
        context.startActivity(intent);
    }
}